import { createStore } from 'vuex'
import router from "@/router";
import createPersistedState from 'vuex-persistedstate';

export default createStore({
  state: {
    token:undefined,
    menuList: "{}",
    userInfo:"{}",
    //是否已经动态绑定了路由的标识
    hasRoutes:false,
    routes:[],
    //当前选中的标签页的名称
    editableTabsValue:'/index',
    editableTabs:[
      {
        title:'首页',
        name:'/index'

      }
    ]
  },
  getters: {
    GET_TOKEN: state => {
      // if(state.token!=undefined){
      //   return state.token
      // }else{
      //   return sessionStorage.getItem("token")
      // }
      return state.token
      //   return sessionStorage.getItem("token")
      },
    GET_MENULIST:state =>{
      return JSON.parse(state.menuList)
      // if(state.menuList!="{}"){
      //   return JSON.parse(state.menuList)
      // }
      // return JSON.parse(sessionStorage.getItem("menuList"));
    },
    GET_USERINFO:state =>{
      return JSON.parse(state.userInfo)
      // return JSON.parse(sessionStorage.getItem("userInfo"));
    },
    GET_ROUTES :state =>{
      return state.routes
    },
    },
  mutations: {
    SET_TOKEN : (state,token)=>{
      state.token = token
      // sessionStorage.setItem("token" ,token);
    },
    SET_MENULIST : (state,menuList)=>{
      state.menuList = JSON.stringify(menuList);
      // sessionStorage.setItem("menuList" ,JSON.stringify(menuList));
    },
    SET_USERINFO : (state,userInfo)=>{
      state.userInfo = JSON.stringify(userInfo);
      // sessionStorage.setItem("userInfo" ,JSON.stringify(userInfo));
    },
    SET_ROUTES_STATE : (state,hasRoutes)=>{
      state.hasRoutes=hasRoutes
    },
    SET_ROUTES:(state,routes)=>{
      state.routes =routes;
    },
    ADD_TABS : (state,tab)=>{
      //如果存在就不添加,path对应的就是editableTabs的name
      if(state.editableTabs.findIndex(e=>e.name===tab.path)===-1){
        state.editableTabs.push({
          title:tab.name,
          name:tab.path
        })
      }
      //使左侧菜单和右侧tab同步选中
      state.editableTabsValue = tab.path
    },
    //重置Tab菜单
    RESET_TABS : (state)=>{
      state.editableTabsValue = '/index';
      state.editableTabs=[
        {
          title:'首页',
          name:'/index'
        }
      ]
    },
    CLEAR_SESSION_DATA: (state) => {
      state.token = undefined;
      state.menuList = "{}";
      state.userInfo = undefined;
    }
  },
  actions: {
    //封装安全退出
    logout({ commit }){
      commit('CLEAR_SESSION_DATA');
      window.sessionStorage.clear();
      router.replace("/login")
    }
  },
  modules: {
  },
  plugins: [//持久化
    createPersistedState({
      storage: window.sessionStorage, // 或者使用 localStorage
    }),
  ],
})
